#pragma once


#include <iostream>
#include <string>
#include <memory>
#include <poll.h>
#include "Log.hpp"
#include "Socket.hpp"



using namespace SocketModule;
using namespace LogModule;


const int gdefaultfd = -1;
#define MAX 4096


//最开始tcpserver只有一个listensockfe
class PollServer
{
public:
    PollServer(int port)
    :_port(port),
    _listen_socket(std::make_unique<TcpSocket>()),
    _isrunning(false)
    {

    }

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        for(int i=0;i<MAX;i++)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        //先把唯一的fd添加到poll中
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
        //revents是在内核中设置的,我们不用关心
    }

    void Loop()
    {
        int timeout = -1;
        _isrunning = true;
        while(_isrunning)
        {
            int n = poll(_fds,MAX,timeout);
            //当有事件发送是,内核会进行修改revents
            switch(n)
            {
                case 0:
                    std::cout << "time out..." << std::endl;
                    break;
                case -1:
                    perror("select");
                    break;
                default:
                    Dispatcher();
                    TestFd();
                    break;
            }
        }
        _isrunning = false;
    }


    void Accepter()
    {
        //listenscokfd就绪了! 获取新链接不就好了吗?
        InetAddr client;
        int newfd = _listen_socket->Accepter(&client);//这里accepter时就不会阻塞了,select已经告诉我了,只拷贝就行了
        if (newfd < 0)
        {
            return;
        }
        else
        {
            std::cout << "获得了一个新链接: " << newfd << " client info: " << client.Addr() << std::endl;
            int pos = -1;
            for(int j = 0;j < MAX ;j++)
            {
                if(_fds[j].fd == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if(pos == -1)
            {
                // _fds进行自动扩容
                LOG(LogLevel::ERROR) << "服务器已经满了....";
                close(newfd);
            }
            else
            {
                _fds[pos].fd = newfd;
                _fds[pos].events = POLLIN;
            }

        }
    }
    void Recver(int i)
    {
        //合法的就绪的,普通的fd
        //要根据协议进行读取
        char buffer[1024];
        ssize_t n = recv(_fds[i].fd,buffer,sizeof(buffer)-1,0);//这里的recv不会阻塞,select已经告诉我们他已经就绪了
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            std::string message = "echo# ";
            message += buffer;
            send(_fds[i].fd,message.c_str(),message.size(),0);
        }
        else if(n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: "<<_fds[i].fd;
            close(_fds[i].fd);
            _fds[i].fd = gdefaultfd;
            _fds[i].events = _fds[i].revents = 0;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: "<<_fds[i].fd;
            close(_fds[i].fd);
            _fds[i].fd = gdefaultfd;
            _fds[i].events = _fds[i].revents = 0;
        }
    }

    void Dispatcher()//rfds就可能会有更多的fd就绪了,就不仅仅是listenfd就绪了
    {
        for(int i=0;i<MAX;i++)
        {
            if(_fds[i].fd==gdefaultfd)
            {
                continue;
            }
            //文件描述符,先得是合法得

            //区分是IO读还是获取新链接
            if(_fds[i].fd == _listen_socket->Fd())
            {
                if(_fds[i].revents & POLLIN)
                {
                    Accepter();//获取新链接
                }
            }
            else
            {
                if(_fds[i].revents & POLLIN)
                {
                    Recver(i);//IO处理
                }
                // else if(_fds[i].revents & POLLOUT)
                // {
                        //write,现在不关心写
                // }
            }   
        }
    }

    void TestFd()
    {
        std::cout << "pollfd: ";
        for(int i = 0;i < MAX; i++)
        {
            if(_fds[i].fd == gdefaultfd)
            {
                continue;
            }
            std::cout << _fds[i].fd << "[" << Events2str(_fds[i].events) << "]";
        }
    }

    std::string Events2str(short events)
    {
        std::string s = (events & POLLIN) ? "EPOLLIN" : "";
        s += (events & POLLOUT) ? "POLLOUT" : "";
        return s;
    }

    ~PollServer()
    {

    }
private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    struct pollfd _fds[MAX];
    // struct pollfd *_fds; //malloc 
};



